<?php include 'functions.php'; echo $html_doctype; ?>
<html>
<head>
<title> Scratch Resources | Share!</title>
<?php
	echo $html_meta;
	echo $html_css;
	echo $html_scripts;
?>
<script type="text/javascript" src="/js/uploadform.js"></script>
</head>

<body>
<!-- HEADER -->
<div id="maincontainer">

	<?php
	include 'header.php';
	?>
	
	<div class="box_fullwidth">
	<h1>Upload File</h1>
	<?php
	if ($resdap_user_rank=='guest') {
		echo "You have to be logged in to upload files. <br>\n<br>\n".
			 '<a href="/login">Log in</a> or <a href="/register">activate your Scratch Account</a> for use with Scratch Resources.<br>'."\n".
			 'Go to <a href="http://scratch.mit.edu">scratch.mit.edu</a> to learn more about Scratch or create a Scratch Account if you do not yet have one.<br>'."\n\n";
	} else {
		$uForm_sent = isset( $_POST['restitle']);
		$uForm_error = false;
		$uForm_errmsg = '';
		if ($uForm_sent) {
			//check all input
			//Recaptcha...
			require_once('recaptchalib.php');
			$privatekey = "6Ldt4gkAAAAAAC_HJ5rcOplZzDfLrKXBlSARiB5q";
			/*$resp = recaptcha_check_answer ($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]);		
			if (!$resp->is_valid) {
				$uForm_error = true;
				$uForm_errmsg .= 'You did not fill in the Text Identification correctly.<br>';
			}*/
			//Form input...
			$restitle = $_POST['restitle'];
			$restype = $_POST['restype'];
			$rescategory = $_POST['rescategory'];
			$respath = ''; //file path on server
			$rescomments = $_POST['rescomments'];
			$resip = $_SERVER['REMOTE_ADDR'];
			//$resuser = $resdap_user_name; >>> DEPRECATED, REPLACED BY $resdap_user_id
			$resdate = date("Y-m-d H:i:s"); //valid format for MySQL Datetime
			//check title
			if (strlen($restitle)==0) {
				$uForm_error = true;
				$uForm_errmsg .= 'Please fill in a title.<br>';
			}
			if (strlen($restitle)>100) {
				$uForm_error = true;
				$uForm_errmsg .= 'The title you entered exceeds the maximum length of 100 characters.<br>';
			}
			//check resource type
			if (strlen($restype)==0 || strlen($restype)>10) {
				$uForm_error = true;
				$uForm_errmsg .= 'Please select a resource type.<br>';
			}
			if (!$uForm_error) {
				if ($_FILES['resfile']['error'] > 0) {
					$uForm_error = true;
					$uForm_errmsg .= 'An error occured with your file upload: '. $_FILES['resfile']['error'] . '<br>';
	  			} else {
		  			$fname = $_FILES['resfile']['name'];
	  				$ftype = $_FILES['resfile']['type'];
	  				$fsize = $_FILES['resfile']['size'];
	  				$ftmpn = $_FILES['resfile']['tmp_name'];
	  				$fExt = $ext = pathinfo($fname, PATHINFO_EXTENSION);
	  				$fAllow = false;
	  				
	  				//check if the uploaded file is valid for the resource type and perform resource type specific scripts if any
	  				switch ($restype) {
			  			case 'sprite': case 'script':
			  			dev_out("$fname of type $ftype by UID $resdap_user_id is a sprite!");
				  			$fAllow = (($ftype=='application/x-sprite' || $ftype=='application/octet-stream') && substr($fname, -7)=='.sprite');
				  			if ($fAllow) {
					  			dev_out('allowed');
					  		}
				  			break;
			  			case 'sound':
				  			$fAllow = (substr($fname, -4)=='.mp3' || substr($fname, -4)=='.wav');
				  			break;
			  			case 'background':
				  			$fAllow = ($ftype=='image/jpeg' || $ftype=='image/pjpeg' || $ftype=='image/png' || $ftype=='image/gif' /*|| $ftype=='image/bmp'*/);
				  			if ($fAllow) {
					  			//resize image to 480x360 and save as png
					  			
								// The file
								$filename = $ftmpn;
								
								// Get new dimensions
								list($width, $height) = getimagesize($filename);
								$new_width = 480;
								$new_height = 360;
								
								// Resample
								switch ($ftype) {
									case 'image/jpeg': case 'image/pjpeg':
										$image = imagecreatefromjpeg($filename);
										break;
									case 'image/png':
										$image = imagecreatefrompng($filename);
										break;
									case 'image/gif':
										$image = imagecreatefromgif($filename);
										break;
									/*case 'image/bmp':
										$image = imagecreatefrombmp($filename);
										break;*/
								}
								$image_p = imagecreatetruecolor($new_width, $new_height);
								imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
								
								// Output
								imagepng($image_p, $ftmpn);
								$fExt = 'png';
				  			}
				  			break;
	  				}
	  				if (!$fAllow) {
		  				$uForm_error = true;
						$uForm_errmsg .= 'The file type of your upload is not supported as a '.$restype.'.<br>';  				
					} else {
						//All checked, add to Database
						resdap_connect();
						// (autoId)      Title                                          Type                                          Category                                          Comments                                          Extension                                  Ip                                          UserID                     Date        
						$qValues = "'" . mysql_real_escape_string($restitle) . "', '" . mysql_real_escape_string($restype) . "', '" . mysql_real_escape_string($rescategory) . "', '" . mysql_real_escape_string($rescomments) . "', '" . mysql_real_escape_string($fExt) . "', '" . mysql_real_escape_string($resip) . "', '" . $resdap_user_id . "', '" . mysql_real_escape_string($resdate) . "');";
						$q =  "INSERT INTO res_resources ( title, type, category, comments, ext, ip, user, date) VALUES(" . $qValues;
						dev_out('redirect required');
						dev_out($q);
						dev_out($ftmpn);
						mysql_query($q) or die(mysql_error());
						move_uploaded_file($ftmpn, '../files/resources/' . mysql_insert_id() . '.' . $fExt);
						resdap_disconnect();
						dev_out('Upload succesful. <br> The file you uploaded will not yet be visible, please wait for the Scratch Resources team to approve it. <br><br> There is no need to upload again.');
					}
	  			}
			}
		}
		if (!$uForm_sent || $uForm_error) {
			if ($uForm_error) {
				echo '<div id="uploadform_errorbox">'.$uForm_errmsg.'</div><br>';
		 	}
			//Upload form
	?>
	
	<div id="uploadform_infobox" class="uploadform_infobox">Vraagteken?</div>
	<form name="uploadform" id="uploadform" class="defaultform wide" enctype="multipart/form-data" method="post" action="/pages/upload.php">
	
	<label for="resfile">File:</label>
	<input type="file" name="resfile" size="37" onChange="checkForm(5)"></input> &nbsp;
	<img src="/files/images/form_u.png" name="resfile_icon" id="resfile_icon"></img><br>
	<input type="hidden" name="MAX_FILE_SIZE" value="5242880"></input> <!-- 5MB -->
	
	<div class="defaultform_radiobox" id="defaultform_radiobox">
		<input type="radio" class="radio" name="restype" value="sprite"     id="sprite"     onChange="setResType('sprite')"></input><label for="sprite">Sprite (.sprite)</label>
		<input type="radio" class="radio" name="restype" value="script"     id="script"     onChange="setResType('script')"></input><label for="script">Script (.sprite)</label>
		<input type="radio" class="radio" name="restype" value="sound"      id="sound"      onChange="setResType('sound')"></input><label for="sound">Sound (.mp3)</label>
		<input type="radio" class="radio" name="restype" value="background" id="background" onChange="setResType('background')"></input><label for="background">Background (.png, .jpg, .jpeg, .gif, .bmp)</label>
	</div>
	
	<label for="rescategory">Category:</label>
	<select name="rescategory" id="rescategory" onChange="checkForm(0)">
  	<option value="none">(none)</option>
	</select>&nbsp;
	<img src="/files/images/form_u.png" name="rescategory_icon" id="rescategory_icon"></img><br>
	<br>
	
	<label for="restitle">Title:</label>
	<input type="text" name="restitle" id="restitle" onChange="checkForm(1)"></input>&nbsp;
	<img src="/files/images/form_u.png" name="restitle_icon" id="restitle_icon"></img><br>
	<br>
	
	<label for="rescomments">Comments:</label>
	<textarea name="rescomments" id="rescomments" onChange="" rows="8"></textarea>&nbsp;
	<img src="/files/images/form_u.png" name="rescomments_icon" id="rescomments_icon"></img><br>
	<br>
	
	<?php
	/*require_once('recaptchalib.php');
	$publickey = "6Ldt4gkAAAAAAE_TfQkjnCbCJikl_GT4QozaqYtk";
	echo recaptcha_get_html($publickey);*/
	?>
	
	<br>
	<input type="submit" value="Upload!" name="submit" id="submit" disabled="true"></input>
	</form>
	
	<?php
		}
	}
	?>
	</div>
	
	<?php include('footer.php'); ?>
</div>
</body>

</html>